import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Popconfirm, Table, Tooltip, MessagePlugin } from 'tdesign-react'
import { EditIcon, MenuUnfoldIcon, DeleteIcon } from 'tdesign-icons-react'
import TableOperateButton from '@/components/Table/TableOperateButton'
import TopSearch from './TopSearch'
import { ApiRequest, apis } from '@/service'

const {
  getModuleList,
  deleteModule,
} = apis.BMService.project

const ModuleList = () => {

  const navigate = useNavigate()

  const [queryParams, setQueryParams] = useState({
    ids: [],
    filterKeyList: ['moduleName'],
    keyword: '',
  })
  const [loading, setLoading] = useState(false)
  const [tableData, setTableData] = useState<any[]>([])
  const [total, setTotal] = useState(0)
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    paging: true
  })

  useEffect(() => {
    getTableData(queryParams)
  }, [queryParams, pagination])

  const getTableData = (queryParams: QueryParamsType) => {
    setLoading(true)
    const params = {
      ...queryParams,
      ...pagination,
    }
    ApiRequest({ api: getModuleList, params, errorCallback: () => { setLoading(false) } }).then((res: ResponseDataType) => {
      const { code = -1, data = [], note = '', total = 0 } = res
      if (code > 0) {
        setTableData(data)
        setTotal(total)
      } else {
        MessagePlugin.error({
          content: note,
          placement: 'top-right',
          duration: 2000
        })
      }
      setLoading(false)
    })
  }

  const toAddPage = () => {
    navigate('/aio/bug-manager/project/add-module')
  }

  const toEditItem = (row: any) => {
    navigate(`/aio/bug-manager/project/add-module`, {
      state: {
        id: row.id
      }
    })
  }

  const toDetailsPage = (row: any) => {
    navigate(`/aio/bug-manager/project/module-details`, {
      state: {
        id: row.id
      }
    })
  }

  const deleteItem = (row: any) => {
    const params = {
      ids: [row.id]
    }
    ApiRequest({ api: deleteModule, params }).then((res: ResponseDataType) => {
      const { code = -1, data = [], note = '', total = 0 } = res
      if (code > 0) {
        getTableData(queryParams)
        MessagePlugin.success({
          content: `已成功删除${total}条数据`,
          placement: 'top-right',
          duration: 2000
        })
      } else {
        MessagePlugin.error({
          content: note,
          placement: 'top-right',
          duration: 2000
        })
      }
    })
  }

  const columns: any = [
    {
      colKey: 'moduleName',
      title: '模块名称',
    },
    {
      colKey: 'projectName',
      title: '所属项目名称',
      cell: ({ row }: { row: any }) => (
        <>{row.projectName[0]?.label}</>
      )
    },
    {
      colKey: 'moduleLeader',
      title: '模块负责人',
      cell: ({ row }: { row: any }) => (
        <>{row.moduleLeader[0]?.label}</>
      )
    },
    {
      colKey: 'operate',
      title: '操作',
      align: 'center',
      width: 60 * 2,
      fixed: 'right',
      cell: ({ row }: { row: any }) => (
        <div className='tdesign-table-demo__table-operations' onClick={(e) => { e.stopPropagation() }}>
          <Tooltip content={'编辑'}>
            <><TableOperateButton Icon={<EditIcon />} onClick={() => { toEditItem(row) }} /></>
          </Tooltip>
          <Tooltip content={'详情'}>
            <><TableOperateButton Icon={<MenuUnfoldIcon />} onClick={() => { toDetailsPage(row) }} /></>
          </Tooltip>
          <Popconfirm
            content={'确定删除此项目吗?'}
            onConfirm={(e) => { deleteItem(row) }}
            onCancel={() => {}}
          >
            <>
              <Tooltip content={'删除'}>
                <><TableOperateButton Icon={<DeleteIcon />} /></>
              </Tooltip>
            </>
          </Popconfirm>
        </div>
      )
    }
  ]

  const onSearch = (fields: any) => {
    const params = {
      ...queryParams,
      ...fields,
      moduleLeader: fields.moduleLeader?.map((item: any) => item.value),
      ids: fields.projectName?.map((item: any) => item.value),
      keyword: fields.moduleName || '',
    }
    delete params.projectName
    delete params.moduleName
    setQueryParams({
      ...params
    })
  }

  const onPageChanage = (pageInfo: PageInfo) => {
    setPagination({
      ...pagination,
      current: pageInfo.current,
      pageSize: pageInfo.pageSize
    })
  }

  return <div className={'content-wrapper'}>
    <Button onClick={toAddPage}>添加模块</Button>
    <Table
      className='bm-table'
      topContent={<TopSearch onSearch={onSearch} />}
      data={tableData}
      columns={columns}
      rowKey={'id'}
      verticalAlign={'top'}
      bordered={true}
      showHeader={true}
      tableLayout={'auto'}
      rowClassName={({ rowIndex }) => `${rowIndex}-class`}
      cellEmptyContent={'--'}
      resizable={false}
      size='small'
      loading={loading}
      pagination={{
        defaultCurrent: 1,
        defaultPageSize: 10,
        total,
        showJumper: true,
        size: 'small',
        onChange: onPageChanage,
        onCurrentChange(current, pageInfo) {
          console.log(current, pageInfo, 'onCurrentChange current');
        },
        onPageSizeChange(size, pageInfo) {
          console.log(size, pageInfo, 'onPageSizeChange size');
        },
      }}
      onPageChange={(pageInfo) => {
        console.log(pageInfo, 'onPageChange');
      }}
      onRowClick={({ row, index, e }) => {
        console.log('onRowClick', { row, index, e });
      }}
    />
  </div>
}

export default ModuleList
